package com.parktech.sun.web.controller.management.sunhz;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.sunhz.IndustryAttachment;
import com.parktech.sun.domain.model.sunhz.Industry;
import com.parktech.sun.domain.model.sunhz.IndustryCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.sunhz.IndustryService;
import com.parktech.sun.utils.FileHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * User: Think
 * Date: 11-1-8
 * Time: 下午8:20
 */
@Controller
@RequestMapping("/management/industries")
public class IndustryController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private IndustryService industryService;

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Autowired
    public IndustryController(IndustryService industryService) {
        this.industryService = industryService;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute IndustrySearchForm industrySearchForm) {

        Page page = new Page(pageSize, industrySearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/sunhz/industrySearch");

        return modelAndView.addObject(
                industryService.search(
                        industrySearchForm.getTitle(), industrySearchForm.getCategory(), industrySearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("industryIds") Long[] industryIds) {
        industryService.deleteAll(industryIds);
        return "redirect:search";
    }

    @ModelAttribute("allCategories")
    public List<IndustryCategory> populateAllCategories() {
        return industryService.listAllCategory();
    }
    @ModelAttribute("industry")
    public Industry populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new Industry();
        }
        return industryService.getById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{industryId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long industryId, Model model) {
        Industry industry = industryService.getById(industryId);
        model.addAttribute(industry);
        return "management/sunhz/industryForm";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new Industry());
        return "management/sunhz/industryForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid Industry industry, BindingResult result,
                       @RequestParam("attachments") MultipartFile[] attachments,
                       @RequestParam("delAttachmentIds") Long[] delAttachmentIds,HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/sunhz/industryForm";
        }
        industryService.clearThenSaveOrUpdateBean(industry);

        if (delAttachmentIds != null) {
            deleteAttachments(industry, delAttachmentIds, request.getSession().getServletContext());
        }

        if (attachments.length > 0) {
            processAttachments(industry, attachments, request.getSession().getServletContext());
        }
        industryService.saveOrUpdateBean(industry);

        return "redirect:/management/industries/search";
    }

    private void deleteAttachments(Industry industry, Long[] delAttachmentIds, ServletContext servletContext) {
        List<IndustryAttachment> attachmentList = industry.getAttachmentList();
        if (attachmentList == null) {
            return ;
        }
        String industryPath = servletContext.getRealPath("/upload/industry/" + industry.getId());
        File industryDir = new File(industryPath);
        if (!industryDir.exists()) industryDir.mkdirs();

        for (Iterator<IndustryAttachment> iterator = attachmentList.iterator(); iterator.hasNext(); ) {
            IndustryAttachment attachment = iterator.next();
            for (Long delAttachmentId : delAttachmentIds) {
                if (attachment.getId().equals(delAttachmentId)) {
                    iterator.remove();
                    attachmentList.remove(attachment);
                    attachment.setIndustry(null);
                    File toDelFile = new File(industryDir, attachment.getName());
                    if (toDelFile.exists()) toDelFile.delete();
                }
            }
        }
    }

    private void processAttachments(Industry industry, MultipartFile[] attachments, ServletContext servletContext) throws IOException {

        String industryPath = servletContext.getRealPath("/upload/industry/" + industry.getId());
        File industryDir = new File(industryPath);
        if (!industryDir.exists()) industryDir.mkdirs();

        List<IndustryAttachment> attachmentList = industry.getAttachmentList();
        if (attachmentList == null) {
            attachmentList = new ArrayList<IndustryAttachment>();
            industry.setAttachmentList(attachmentList);
        }
        for (MultipartFile attachment : attachments) {
            if (attachment == null || attachment.isEmpty()) {
                continue;
            }
            String originalFilename = attachment.getOriginalFilename();
            File target = new File(industryDir, attachment.getOriginalFilename());
            if (target.exists()) {
                target.delete();
            } else {
                attachmentList.add(new IndustryAttachment(originalFilename, industry));
            }

            FileHelper.saveFile(attachment.getInputStream(), target);
        }
    }
}
